/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/spf13/cobra"
	"gitlab.ctyuncdn.cn/tai/infra/cloud-controller/internal/app"
)

var (
	appInstance *app.App
	version     = "v1.0.0"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "cloud-controller",
	Short: "Cloud-Controller: Unified job and cluster management",
	Long:  `Cloud-Controller is a unified platform for managing jobs, clusters, and resources in a cloud-native environment.`,
	Run: func(cmd *cobra.Command, args []string) {
		appInstance = app.NewApp()
		go func() {
			appInstance.Run()
		}()
		// Wait for shutdown signal
		sigs := make(chan os.Signal, 1)
		signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
		<-sigs
		fmt.Println("\nReceived shutdown signal. Exiting...")
		appInstance.Stop()
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.AddCommand(configCmd)
	rootCmd.AddCommand(healthCmd)
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(shutdownCmd)
}

// configCmd provides configuration commands
var configCmd = &cobra.Command{
	Use:   "config",
	Short: "Show or edit configuration",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Configuration management is not yet implemented.")
	},
}

// healthCmd provides a health check command
var healthCmd = &cobra.Command{
	Use:   "health",
	Short: "Check application health",
	Run: func(cmd *cobra.Command, args []string) {
		appInstance = app.NewApp()
		if appInstance.HealthCheck() {
			fmt.Println("Application is healthy.")
		} else {
			fmt.Println("Application is NOT healthy.")
		}
	},
}

// versionCmd provides version information
var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Show version information",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("Cloud-Controller version: %s\n", version)
	},
}

// shutdownCmd provides a graceful shutdown command
var shutdownCmd = &cobra.Command{
	Use:   "shutdown",
	Short: "Gracefully shut down the application",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Initiating graceful shutdown...")
		if appInstance != nil {
			appInstance.Stop()
			fmt.Println("Application stopped.")
		} else {
			fmt.Println("Application is not running.")
		}
	},
}
